/* Copyright 2015 Therp BV <http://therp.nl>
 * Copyright 2017-2018 Jairo Llopis <jairo.llopis@tecnativa.com>
 * Copyright 2020 Brainbean Apps (https://brainbeanapps.com)
 * License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). */

odoo.define("web_advanced_search", function (require) {
    "use strict";

    var core = require("web.core");
    var Domain = require("web.Domain");
    var DomainSelectorDialog = require("web.DomainSelectorDialog");
    var field_registry = require("web.field_registry");
    var FieldManagerMixin = require("web.FieldManagerMixin");
    var FiltersMenu = require("web.FiltersMenu");
    var human_domain = require("web_advanced_search.human_domain");
    var SearchView = require("web.SearchView");
    var Widget = require("web.Widget");
    var Char = core.search_filters_registry.get("char");
    var config = require("web.config");
    var _lt = core._lt;

    SearchView.include({
        custom_events: _.extend({}, SearchView.prototype.custom_events, {
            "get_dataset": "_on_get_dataset",
        }),

        /**
         * Add or update a `dataset` attribute in event target
         *
         * The search view dataset includes things such as the model, which
         * is required to make some parts of search views smarter.
         *
         * @param {OdooEvent} event The target will get the dataset.
         */
        _on_get_dataset: function (event) {
            event.target.dataset = this.dataset;
            event.stopPropagation();
        },

        start: function () {
            var self = this;
            return this._super.apply(this, arguments).then(function () {
                self.quick_filters_menu = $('<button class="btn btn-default"><i class="fa fa-search">快捷搜索</i></button>')
                    .on('click', function (ev) {
                        self.filters_menu.advanced_search_open();
                    });
                return self.quick_filters_menu.insertBefore(
                    self.filters_menu.$el
                );
            });
        },

    });

    /**
     * An almost dummy search proposition, to use with domain widget
     */
    var AdvancedSearchProposition = Widget.extend({

        /**
         * @override
         */
        init: function (parent, model, domain) {
            this._super(parent);
            this.model = model;
            this.domain = new Domain(domain);
            this.domain_array = domain;
        },

        /**
         * Produce a filter descriptor for advanced searches.
         *
         * @returns {Object} In the format expected by `web.FiltersMenu`.
         */
        get_filter: function () {
            return {
                attrs: {
                    domain: this.domain_array,
                    // TODO Remove when merged
                    // https://github.com/odoo/odoo/pull/25922
                    string: human_domain.getHumanDomain(
                        this,
                        this.model,
                        this.domain_array
                    ),
                },
                children: [],
                tag: "filter",
            };
        },
    });

    // Add advanced search features
    FiltersMenu.include({
        custom_events: _.extend({}, FiltersMenu.prototype.custom_events, {
            "domain_selected": "advanced_search_commit",
        }),

        events: _.extend({}, FiltersMenu.prototype.events, {
            "click .o_add_advanced_search": "advanced_search_open",
        }),

        /**
         * Handle dropdown hidden event to prevent the menu from closing when using a
         * relational field
         *
         * @override
         */
        start: function () {
            this._super.apply(this, arguments);
            this.$el.on('hide.bs.dropdown', function() {
                var $modal = $('.o_technical_modal.show');
                return !(($modal.length && !$modal.has($(this)).length) || $('body.oe_wait').length);
            });
        },

        /**
         * @override
         */
        init: function () {
            this._super.apply(this, arguments);
            this.trigger_up("get_dataset");
        },

        /**
         * Open advanced search dialog
         *
         * @returns {$.Deferred} The opening dialog itself.
         */
        advanced_search_open: function () {
            var domain_selector_dialog = new DomainSelectorDialog(
                this,
                this.dataset.model,
                "[]",
                {
                    debugMode: config.debug,
                    readonly: false,
                    followRelations: false,
                }
            );
            domain_selector_dialog.opened(function () {
                domain_selector_dialog.domainSelector._onAddFirstButtonClick();
            });
            return domain_selector_dialog.open();
        },

        /**
         * Apply advanced search on dialog save
         *
         * @param {OdooEvent} event A `domain_selected` event from the dialog.
         */
        advanced_search_commit: function (event) {
            _.invoke(this.propositions, "destroy");
            var proposition = new AdvancedSearchProposition(
                this,
                this.dataset.model,
                event.data.domain
            );
            this.propositions = [proposition];
            this._commitSearch();
        },
    });

    return {
        AdvancedSearchProposition: AdvancedSearchProposition
    };
});
